package com.cdvtc.fengchao.Servlet;

import com.cdvtc.fengchao.dao.ProductsDAO;
import com.cdvtc.fengchao.model.Product;
import com.cdvtc.fengchao.dao.SuppliersDAO;
import com.cdvtc.fengchao.model.Supplier;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/product-detail") // 独立路径，避免与其他Servlet冲突
public class ProductDetailServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取商品ID参数
        String id = request.getParameter("id");

        // 2. 校验参数（ID不能为空或非数字）
        if (id == null || !id.matches("\\d+")) { // 确保ID为数字
            response.sendRedirect(request.getContextPath() + "/error.jsp");
            return;
        }

        // 3. 从数据库查询商品信息
        ProductsDAO productDAO = new ProductsDAO();
        Product product = productDAO.getProductById(id);

        // 4. 处理商品不存在的情况
        if (product == null) {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
            return;
        }

        // 5. 查询供应商信息
        SuppliersDAO supplierDAO = new SuppliersDAO();
        Supplier supplier = supplierDAO.getSupplierById(product.getSupplierId());

        // 6. 查询相关推荐商品（同类别，排除当前商品）
        List<Product> relatedProducts = productDAO.getRelatedProducts(product.getCategory(), id);

        // 7. 将数据存入request作用域
        request.setAttribute("product", product);
        request.setAttribute("supplier", supplier);
        request.setAttribute("relatedProducts", relatedProducts);

        // 8. 转发到商品详情页
        request.getRequestDispatcher("/product.jsp").forward(request, response);
    }
}